package com.aigao.golf.management.user.controller.root;

import com.aigao.golf.Utils.DaoUtil;
import com.aigao.golf.common.base.BaseController;
import com.aigao.golf.common.base.Constants;
import com.aigao.golf.common.base.PageController;
import com.aigao.golf.common.result.ResultEnum;
import com.aigao.golf.common.result.ResultTo;
import com.aigao.golf.management.user.model.CmOrg;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author QiangHe
 * @date 2018/1/11 21:25
 */
@RestController
@RequestMapping("/root/organization")
public class OrganizationController extends PageController<CmOrg> {

    @PostMapping("/list")
    public ResultTo list(Integer pageStart , Integer pageLength, String pageOrder) {
        Map<String,Object> param = new HashMap<>(2);
        param.put("creator", Constants.ROOT_NAME);
        param.put("flag",0);
        return dataPage(pageStart,pageLength,pageOrder,param);
    }

    /**
     * 添加机构
     *
     * @return
     */
    @PostMapping("/add")
    public ResultTo add(String name) {
        CmOrg org = new CmOrg();
        org.setName(name);
        org.setCreator(Constants.ROOT_NAME);
        org.setParentId(Constants.ROOT_NAME);
        org.setCreateTime(new Date());
        if (adaptService.insertSelective(org) == 1) {
            return new ResultTo(org);
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "保存失败");
        }
    }

    @PostMapping("/update")
    public ResultTo update(String id,
                              @RequestParam(name = "name") String name) {
        CmOrg org = new CmOrg();
        org.setId(id);
        org.setName(name);
        org.setCreator(Constants.ROOT_NAME);
        org.setParentId(Constants.ROOT_NAME);
        org.setCreateTime(new Date());
        if (name != null) {
            org.setUpdateTime(new Date());
        }
        Example example = new Example(CmOrg.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        if (adaptService.updateByExampleSelective(org, example) == 1) {
            return new ResultTo(ResultEnum.SUCCESS, "更新成功");
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "更新失败");
        }
    }

    /**
     * 删除机构
     *
     * @param id
     * @return
     */
    @PostMapping("/remove")
    public ResultTo remove(String id) {
        if (DaoUtil.deleteById(adaptService, id, CmOrg.class) == 1) {
            return new ResultTo(ResultEnum.SUCCESS, "删除成功");
        } else {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "删除失败");
        }
    }
}
